﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB;
using MongoDB.Linq;

namespace Blog_Domain.Repositories
{
    public class PostRepository : IPostRepository
    {

        public bool Save(Post post)
        {
            var mongo = new Mongo();
            mongo.Connect();

            var blog = mongo.GetDatabase("blog");
            var postCollection = blog.GetCollection<Post>();

            post.Comments = new List<Comment>();
            post.Comments.Add(new Comment
            {
                Body = "",
                Email = ""
            });
            postCollection.Save(post);

            mongo.Disconnect();

            return !String.IsNullOrEmpty(post.Id.ToString());
        }

        public List<Post> GetAll()
        {
            var mongo = new Mongo();
            mongo.Connect();
            var blog = mongo.GetDatabase("blog");
            var posts = blog.GetCollection<Post>().FindAll().Documents;            
            return posts.ToList();
        }

        public Post GetById(string id)
        {
            var mongo = new Mongo();
            mongo.Connect();
            var blog = mongo.GetDatabase("blog");

            
            Oid specId = new Oid(id);

            var post = blog.GetCollection<Post>().FindOne(specId);

            mongo.Disconnect();

            return post;
        }

        public void Update(Post post)
        {
            var mongo = new Mongo();
            mongo.Connect();

            var blog = mongo.GetDatabase("blog");

            blog.GetCollection<Post>().Update(post, post.Id);

            mongo.Disconnect();
        }
    }
}
